package edu.gdkm.test;

import edu.gdkm.sql.dao.CategoryMapper;
import edu.gdkm.sql.dao.ProductMapper;
import edu.gdkm.sql.pojo.Category;
import edu.gdkm.sql.pojo.Product;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class Main {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private CategoryMapper categoryMapper;

    private ProductMapper productMapper;


    {
        String resources = "mybatis-config.xml";
        // 创建流
        Reader reader = null;
        try {
            // 读取mybatis-config.xml文件到reader对象中
            reader = Resources.getResourceAsReader(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 初始化mybatis, 创建SqlSessionFactory类的对象
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        // 创建session对象
        sqlSession = sqlSessionFactory.openSession(true);
        productMapper = sqlSession.getMapper(ProductMapper.class);
        categoryMapper = sqlSession.getMapper(CategoryMapper.class);

    }
    public static void main(String[] args) {

        while (true) {
            System.out.println("请输入操作：");
            System.out.println("1:查询商品");
            System.out.println("2:查询用户订单");
            System.out.println("请选择：");
            int i = new java.util.Scanner(System.in).nextInt();
            switch (i) {
                case 1:
                    System.out.println("请输入商品名：");
                    String name = new java.util.Scanner(System.in).nextLine();
                    new Main().showProduct(name);
                    break;
                case 2:
                    System.out.println("请输入用户名：");
                    String username = new java.util.Scanner(System.in).nextLine();
                    new Main().showOrders(username);
                    break;
                default:
                    System.out.println("输入错误");
            }
        }

    }
    public void showProduct(String name){
        try {
            Product product = productMapper.findByName(name);
            if (product != null) {
                System.out.println("产品名称: " + product.getGoodsname());
                System.out.println("产品价格: " + product.getPrice());
            } else {
                System.out.println("未找到名称为 " + name + " 的产品");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询产品时发生错误");
        }

    }
    public void showOrders(String username){

    }
}
